package icasue.runninginvoke.task.inteceptors;

import com.alibaba.fastjson.JSON;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import icasue.runninginvoke.task.redis.AsyncTaskOperate;

import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.List;

/**
 * @Author: Qiao Hang
 * @CreateDate: 2020/11/11 下午4:53
 * @UpdateDate:
 * @Description:
 */
public class RibbonChooseResultInterceptor implements ClientHttpRequestInterceptor {

    AsyncTaskOperate asyncTaskOperate;

    public RibbonChooseResultInterceptor(AsyncTaskOperate asyncTaskOperate){
        this.asyncTaskOperate = asyncTaskOperate;
    }

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        List<String> task = request.getHeaders().remove("taskId");
        List<String> classInfo = request.getHeaders().remove("class");
        List<String> methodInfo = request.getHeaders().remove("method");
        List<String> descriptionInfo = request.getHeaders().remove("description");
        HashMap<String, Object> identityInfo = new HashMap<String, Object>() {{
            URI uri = request.getURI();
            put("host", uri.getHost());
            put("port", uri.getPort());
            put("timestamp", System.currentTimeMillis());
            put("taskId", task.get(0));
            put("class", classInfo.get(0));
            put("method", methodInfo.get(0));
            put("description", descriptionInfo.get(0));
        }};
        // update to identity.
        asyncTaskOperate.updateIdentity(task.get(0),JSON.toJSONString(identityInfo));
        return execution.execute(request, body);
    }
}
